package cc.wubo.jpa;

import java.util.concurrent.TimeUnit;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import cc.wubo.jpa.entity.User;
import cc.wubo.jpa.repository.UserRepository;
@ComponentScan
@EnableJpaRepositories
@EnableTransactionManagement
public class App {
	
	private UserRepository ur = null;
	@Before
	public void init(){
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
		ur = context.getBean(UserRepository.class);
	}
	 @Test
	public void save(){
		 User u = new User();
				 u.setName("zhangsan");
		ur.save(u);
	}
	 /**
	  * 实现乐观锁的步骤:
	  * 		1. Entity里面要添加一个字段,该字段用@Version标注
	  * 模拟并发修改:
	  * 	在查询一条数据后让程序睡几秒中,然后手动去修改数据库版本号,这样就会发生冲突
	  * 	再次查询并修改,即可解决
	  * @throws Exception
	  */
	 @Test
	 public void update() throws Exception{
		 User user = ur.findOne(1);
		 System.out.println(user);
		 TimeUnit.SECONDS.sleep(10);
		 user.setName("lisi");
		 ur.save(user);
	 }
	 
	 @Test
	 public void OPTIMISTIC_FORCE_INCREMENT(){
		 User user = ur.getById(1);
		 System.out.println(user);
		 user.setName("lisi");
		 ur.save(user);
	 }
	 
	

}
